package com.sjtu.rental.servlet;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sjtu.rental.common.ImageHepler;

public class UploadController extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -717572927501293097L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		// 初始文件存储路径
		String savePath = generateDir();

		// 存储文件
		processUpload(request, response, savePath);
		processUpload(request, response, getServletConfig().getServletContext()
				.getRealPath("/Cut/upload"));

	}

	/*
	 * 存储方法
	 */
	@SuppressWarnings("unchecked")
	public void processUpload(HttpServletRequest request,
			HttpServletResponse response, String savePath) {

		// 文件项目工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 缓存大小为512KB
		factory.setSizeThreshold(524288);
		// 临时文件夹
		// factory.setRepository(new File(savePath + "/temp"));
		// 初始化上传控件
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 文件大小最大3MB
		// upload.setSizeMax(3145728);
		upload.setHeaderEncoding("UTF-8");
		List fileList = null;
		try {
			fileList = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}

		Iterator<FileItem> it = fileList.iterator();
		String name = "";
		String filename = "";
		while (it.hasNext()) {
			FileItem item = it.next();
			// 如果不是表单域,表单域例如<input type="button" id="button" />.
			if (!item.isFormField()) {
				name = item.getName();
				if (name != null && !name.trim().equals("")) {
					filename = generateFileName(name);
					File file = new File(savePath + "/" + filename);
					try {
						item.write(file);
						String imgstr = request.getContextPath();
						imgstr = imgstr + "/userupload/" + filename;
						BufferedImage bi = ImageIO.read(file);
						if (bi != null) {
							// 将图片地址反馈给index.jsp页面
							response.getWriter().write(
									imgstr + "?size=" + bi.getWidth() + "x"
											+ bi.getHeight());
						} else {
							response.getWriter().write(imgstr);
						}
						// RequestDispatcher
						// requestdispatch=this.getServletConfig().getServletContext().getRequestDispatcher("/index.jsp?width="+bi.getWidth()+"&height="+bi.getHeight());
						// requestdispatch.forward(request,response);

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/*
	 * 初始化文件存储路径 即在tomcat的webapps\ImageUploadByUploadify下建立文件夹upload和upload/temp
	 * upload用来存储图片,temp文件夹做缓存
	 */
	private String generateDir() {
		String pathString = getServletConfig().getServletContext().getRealPath(
				"/userupload");
		String tempString = getServletConfig().getServletContext().getRealPath(
				"/Cut/upload");
		File dirPath = new File(pathString);
		File dirTemp = new File(tempString);
		if (!dirPath.exists()) {
			dirPath.mkdirs();
		}
		if (!dirTemp.exists()) {
			dirTemp.mkdirs();
		}
		return pathString;
	}

	/*
	 * 生成文件名
	 */
	private String generateFileName(String name) {
		long currentTime = System.currentTimeMillis();
		int i = (int) (Math.random() * 1000D + 1.0D);
		long result = currentTime + i;
		String filename = String.valueOf(result) + getFileExt(name);
		return filename;
	}

	/*
	 * 获取文件格式
	 */
	private String getFileExt(String name) {
		int pos = name.lastIndexOf(".");
		if (pos > 0) {
			return name.substring(pos).toLowerCase();
		} else {
			return name.toLowerCase();
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int imageWidth = Math.round(Float.parseFloat(request
				.getParameter("imageW")));
		int imageHeight = Math.round(Float.parseFloat(request
				.getParameter("imageH")));
		int cutTop = Math.round(Float
				.parseFloat(request.getParameter("imageY")));
		int cutLeft = Math.round(Float.parseFloat(request
				.getParameter("imageX")));
		int dropWidth = Math.round(Float.parseFloat(request
				.getParameter("selectorW")));
		int dropHeight = Math.round(Float.parseFloat(request
				.getParameter("selectorH")));
		String picture = request.getParameter("imageSource");
		Rectangle rec = new Rectangle(cutLeft, cutTop, dropWidth, dropHeight);
		File file = new File(request.getSession().getServletContext()
				.getRealPath("/")
				+ "/Cut/" + picture);

		try {
			saveSubImage(new File(request.getSession().getServletContext()
					.getRealPath("/")
					+ picture), file, imageWidth, imageHeight, rec);
		} catch (IOException e) {
			e.printStackTrace();
		}
		response.setContentType("text/html;charset=GBK");
		response.setBufferSize(1024);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print("Cut/" + picture);
		out.flush();
		out.close();
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
	}

	private void saveSubImage(File srcImageFile, File descDir, int width,
			int height, Rectangle rect) throws IOException {
		ImageHepler.cut(srcImageFile, descDir, width, height, rect);
	}

}
